﻿using System.Collections.Generic;
using System.Data;
using System.Data.Linq;
using System.Collections.ObjectModel;
using BusinessLayer;

namespace MvcOSGi.Shell.Infra
{
    public static class IMultipleResultsExtensions
    {
        public static IEnumerable<TElement> GetResult<TElement>(this IEnumerable<IMultipleResults> values)
        {
            if (!values.IsNullOrEmpty())
            {
                foreach (var value in values)
                {
                    if (value == null) continue;
                    var result = value.GetResult<TElement>();
                    if (!result.IsNullOrEmpty()) return result;
                }
            }
            return new TElement[] { };
        }

        public static ReadOnlyCollection<TElement> GetReadOnlyCollection<TElement>(this IEnumerable<IMultipleResults> values)
        {
            if (!values.IsNullOrEmpty())
            {
                foreach (var value in values)
                {
                    var bag = value as MultipleResultsBag;
                    if (bag == null) continue;
                    var result = bag.GetReadOnlyCollection<TElement>();
                    if (!result.IsNullOrEmpty()) return result;
                }
            }
            return new ReadOnlyCollection<TElement>(new TElement[] { });
        }

        public static DataTable GetDataTable(this IEnumerable<IMultipleResults> values, string tableName)
        {
            if (!values.IsNullOrEmpty() && !string.IsNullOrWhiteSpace(tableName))
            {
                foreach (var value in values)
                {
                    var bag = value as MultipleResultsBag;
                    if (value == null) continue;
                    DataTable result = bag[tableName];
                    if (result != null) return result;
                }
            }
            return null;
        }
       /* 
public static IEnumerable<TElement> GetResult<TElement>(this IDictionary<string, IMultipleResults> values, string key)
        {
            if(!values.IsNullOrEmpty() && values.ContainsKey(key))
            {
                var result = values.FirstOrDefault(i => i.Key == key && i.Value is TElement).Value.GetResult<TElement>();
                if(!result.IsNullOrEmpty()) return result;
            }
            return new TElement[] { };
        }*/
    }
}
